﻿using LiveCharts;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using Sunny.UI;
using SuperMap.Data;
using SuperMap.Realspace;
using SuperMap.UI;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Windows.Forms;
using Ycjw.PipeLine.WPF;

namespace Ycjw.PipeLine.BigScreen
{
    /****************************************************************************************/
    /*
    功    能:放置三维场景的DocWindow
    作    者: RenZachary
    联系方式: rzcgis@foxmail.com（QQ455745253）
    生成日期: 2021年3月24日
    修改日志: 
    版权说明: @2021 西安云创经纬信息科技有限公司 版权所有 All right reserved.
    注    意: 本内容仅限于云创经纬公司内部使用，禁止用于商业目的。
    */
    /****************************************************************************************/
    public partial class FullScreeFrameworkEx2 : UIForm, IResposeWPF
    {
        public UIPanel GetCenterPanel()
        {
            return this.uiPanelCenter;
        }
        #region 构造数据
        public void InitData(int tag = 100)
        {
            if (m_FloatWindow == null) return;
            //InitData1(tag);
            InitData2(tag);
            InitData3(tag);
            InitData4(tag);
        }
        private void InitData1(int tag = 100)
        {
            /*
            for (int i = m_FloatWindow.StackPanel01.Children.Count - 1; i >= 0; i--)
            {
                if (m_FloatWindow.StackPanel01.Children[i] is AngularGauge)
                {
                    m_FloatWindow.StackPanel01.Children.RemoveAt(i);
                }
            }
            */
            AngularGauge cc = new AngularGauge
            {
                Value = 1.7*tag,
                FromValue = 50,
                ToValue = 2.5*tag,
                LabelsStep = 50,
                TicksStep = 25,
                Wedge = 300,
                TicksForeground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Yellow),
                Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.BlanchedAlmond),
                FontWeight = new System.Windows.FontWeight(),
                FontSize = 16,
                SectionsInnerRadius = .5
            };
            //m_FloatWindow.StackPanel01.Children.Add(cc);
            cc.Sections.Add(new AngularSection() { FromValue = 50, ToValue = 200, Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Gold) });
            cc.Sections.Add(new AngularSection() { FromValue = 200, ToValue = 250, Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.AliceBlue) });
        }
        private void InitData2(int tag = 100)
        {
            for (int i = m_FloatWindow.StackPanel02.Children.Count - 1; i >= 0; i--)
            {
                if (m_FloatWindow.StackPanel02.Children[i] is PieChart)
                {
                    m_FloatWindow.StackPanel02.Children.RemoveAt(i);
                }
            }
            PieChart cc = new PieChart
            {
                LegendLocation = LegendLocation.Right,
                Margin = new System.Windows.Thickness(20,20,20,20),                
                ChartLegend = new DefaultLegend()
                {
                    Foreground = System.Windows.Media.Brushes.White
                }
            };
            m_FloatWindow.StackPanel02.Children.Add(cc);
            SeriesCollection pieSeriesCollection = new SeriesCollection
            {
                new PieSeries
                {
                    Title = "70年代",
                    Values = new ChartValues<ObservableValue> { new ObservableValue(8*tag) },
                    DataLabels = true,
                    LabelPosition = PieLabelPosition.OutsideSlice,
                    Fill = NewBrush(System.Windows.Media.Colors.Blue)
        },
                new PieSeries
                {
                    Title = "80年代",
                    Values = new ChartValues<ObservableValue> { new ObservableValue(84*tag) },
                    DataLabels = true,
                    LabelPosition = PieLabelPosition.OutsideSlice,
                    Fill = NewBrush(System.Windows.Media.Colors.Green)
                },
                new PieSeries
                {
                    Title = "90年代",
                    Values = new ChartValues<ObservableValue> { new ObservableValue(600 * tag) },
                    DataLabels = true,
                    LabelPosition = PieLabelPosition.OutsideSlice,
                    Fill = NewBrush(System.Windows.Media.Colors.Yellow)
                },
                new PieSeries
                {
                    Title = "00年代",
                    Values = new ChartValues<ObservableValue> { new ObservableValue(1000 * tag) },
                    DataLabels = true,
                    LabelPosition = PieLabelPosition.OutsideSlice,
                    Fill = NewBrush(System.Windows.Media.Colors.Pink)
                },
                new PieSeries
                {
                    Title = "10年代",
                    Values = new ChartValues<ObservableValue> { new ObservableValue(900 * tag) },
                    DataLabels = true,
                    LabelPosition = PieLabelPosition.OutsideSlice,
                    Fill = NewBrush(System.Windows.Media.Colors.Azure)
                },
                new PieSeries
                {
                    Title = "20年代",
                    Values = new ChartValues<ObservableValue> { new ObservableValue(8 * tag) },
                    DataLabels = true,
                    LabelPosition = PieLabelPosition.OutsideSlice,
                    Fill = NewBrush(System.Windows.Media.Colors.IndianRed)
                }
            };
            cc.Series.AddRange(pieSeriesCollection);
        }

        Func<double, string> FormatterT { get; set; }
        Func<double, string> FormatterS { get; set; }
        private void InitData3(int tag = 100)
        {
            for (int i = m_FloatWindow.StackPanel03.Children.Count-1; i >=0;i--) 
            {
                if(m_FloatWindow.StackPanel03.Children[i] is CartesianChart)
                {
                    m_FloatWindow.StackPanel03.Children.RemoveAt(i);
                }
            }
            CartesianChart cc = new CartesianChart
            {
                LegendLocation = LegendLocation.Right,
                ChartLegend = new DefaultLegend()
                {
                    Foreground = System.Windows.Media.Brushes.White
                }
            };
            m_FloatWindow.StackPanel03.Children.Add(cc);
            //新建一条文件大小的柱状图
            ColumnSeries sizeseries = new ColumnSeries();
            sizeseries.Fill = NewBrush(System.Windows.Media.Colors.Blue);
            //新建一条温度的柱状图
            ColumnSeries templeseries = new ColumnSeries();
            templeseries.Fill = NewBrush(System.Windows.Media.Colors.Yellow);
            //添加两个纵坐标的单位
            FormatterT = value => value + "千米";
            FormatterS = value => value + "平方千米";

            templeseries.Title = "长度";
            
            //温度的柱状图依赖于第一条纵坐标
            templeseries.ScalesYAt = 0;
            Axis axisT = new Axis { Title = "千米°" ,LabelFormatter = FormatterT };

            sizeseries.Title = "面积";
            //文件大小的柱状图依赖于第二条纵坐标
            sizeseries.ScalesYAt = 1;
            Axis axisS = new Axis { Title = "平方千米", LabelFormatter = FormatterS };

            cc.AxisY.Add(axisT);
            cc.AxisY.Add(axisS);

            Separator sp = DefaultAxes.CleanSeparator;
            sp.Step = 1;
            cc.AxisX.Add(new Axis()
            {
                Title = "区域",
                Labels = new List<string>() { "莲湖", "雁塔", "长安", "灞桥","未央","碑林" },
                LabelsRotation = -45,
                Separator = sp
            });

            List<double> temperature = new List<double>() { 100, 200, 150, 879, 34, 432 };
            for(var t = 0;t < temperature.Count;t++)
            {
                temperature[t] += tag*tag;
            }
            templeseries.Values = new ChartValues<double>(temperature);
            List<double> filesize = new List<double>() { 0.4, 1.5, 8.9, 0.9, 5.5, 10.0 };
            for (var t = 0; t < filesize.Count; t++)
            {
                filesize[t] += tag/100;
            }
            sizeseries.Values = new ChartValues<double>(filesize);

            var SeriesCollection = new SeriesCollection { };
            SeriesCollection.Add(templeseries);
            SeriesCollection.Add(sizeseries);
            cc.Series.AddRange(SeriesCollection);
        }

        private void InitData4(int tag = 100)
        {
            for (int i = m_FloatWindow.StackPanel04.Children.Count - 1; i >= 0; i--)
            {
                if (m_FloatWindow.StackPanel04.Children[i] is CartesianChart)
                {
                    m_FloatWindow.StackPanel04.Children.RemoveAt(i);
                }
            }
            CartesianChart cc = new CartesianChart
            {
                LegendLocation = LegendLocation.Right,
                Hoverable = true,
                ChartLegend = new DefaultLegend()
                {
                    Foreground = System.Windows.Media.Brushes.White
                }
            };
            m_FloatWindow.StackPanel04.Children.Add(cc);
            var seriesCollection = new SeriesCollection
            {
                new StackedAreaSeries
                {
                    Title = "莲湖",
                    DataLabels = false,
                    Values = new ChartValues<double>
                    {
                        (.228),
                        (.285),
                        (.366),
                        (.478),
                        (.629),
                        (.808),
                        (1.031),
                        (1.110)
                    },
                    LineSmoothness = 0,
                    StackMode = StackMode.Percentage,
                    Fill = NewBrush(System.Windows.Media.Colors.Aqua)
                },
                new StackedAreaSeries
                {
                    Title = "雁塔",
                    DataLabels = false,
                    Values = new ChartValues<double>
                    {
                        (.339),
                        (.424),
                        (.519),
                        (.618),
                        (.727),
                        (.841),
                        (.942),
                        (.972)
                    },
                    LineSmoothness = 0,
                    StackMode = StackMode.Percentage,
                    Fill = NewBrush(System.Windows.Media.Colors.Bisque)
                },
                new StackedAreaSeries
                {
                    Title = "灞桥",
                    DataLabels = false,
                    Values = new ChartValues<double>
                    {
                        (1.395),
                        (1.694),
                        (2.128),
                        (2.634),
                        (3.213),
                        (3.717),
                        (4.165),
                        (4.298)
                    },
                    LineSmoothness = 0,
                    StackMode = StackMode.Percentage,
                    Fill = NewBrush(System.Windows.Media.Colors.Navy)
                },
                new StackedAreaSeries
                {
                    Title = "长安",
                    DataLabels = false,
                    Values = new ChartValues<double>
                    {
                        (.549),
                        (.605),
                        (.657),
                        (.694),
                        (.723),
                        (.729),
                        (.740),
                        (.742)
                    },
                    LineSmoothness = 0,
                    StackMode = StackMode.Percentage,
                    Fill = NewBrush(System.Windows.Media.Colors.DarkGreen)
                },
                new StackedAreaSeries
                {
                    Title = "未央",
                    DataLabels = false,
                    Values = new ChartValues<double>
                    {
                        (.149),
                        (.605),
                        (.657),
                        (.604),
                        (.723),
                        (.719),
                        (.740),
                        (.642)
                    },
                    LineSmoothness = 0,
                    StackMode = StackMode.Percentage,
                    Fill = NewBrush(System.Windows.Media.Colors.DarkOrange)
                }
            };
            Separator sp = DefaultAxes.CleanSeparator;
            sp.Step = 1;
            cc.AxisX.Add(new Axis()
            {
                Labels =new List<string>() { "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", },
                LabelsRotation = -45,
                Separator = sp,
            });;
            cc.AxisY.Add(new Axis() { Title = "故障率", LabelFormatter = val => (val * 100).ToString("N") + " %"});
            cc.Series.AddRange(seriesCollection);
        }
        System.Windows.Media.Brush NewBrush(System.Windows.Media.Color color)
        {
            return null;
            /*
            var brush = new System.Windows.Media.SolidColorBrush();
            brush.Color = color;
            brush.Opacity = .3;
            return brush;
            */
        }
        #endregion
        public SceneControl SceneControl { get; set; }
        /// <summary>
        /// 控制屏幕图层
        /// </summary>
        public void AddScreenLayer()
        {
            if (SceneControl == null) return;
            var screenLayer = this.SceneControl.Scene.ScreenLayer;
            screenLayer.Clear();
            var logoPath = Commons.Paths.ApplicationResourcesDir + "\\BigScreen\\title01.png";
            var logoWidth = 600;
            var left = (this.SceneControl.Width) / 2;
            //向三维屏幕图层中添加几何对象
            GeoPicture3D geoPicture3D = new GeoPicture3D(logoPath, new Point3D(left, 40, 0), logoWidth, 80, 0);
            screenLayer.XUnit = ScreenCoordinateUnit.Pixel;
            screenLayer.YUnit = ScreenCoordinateUnit.Pixel;
            screenLayer.Add(geoPicture3D, "logo");
            SceneControl.Refresh();
        }
        BForm m_FloatWindow;
        public FullScreeFrameworkEx2()
        {
            InitializeComponent();
            this.Width = Screen.PrimaryScreen.Bounds.Width;
            this.Height = Screen.PrimaryScreen.Bounds.Height;
            this.WindowState = FormWindowState.Maximized;
        }
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);

            if (m_FloatWindow == null) return;
            m_FloatWindow.Width = this.Width;
            m_FloatWindow.Height = this.Height;
        }
        protected override void OnLocationChanged(EventArgs e)
        {
            if (m_FloatWindow == null) return;
            m_FloatWindow.Left = this.Left;
            m_FloatWindow.Top = this.Top;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            InitChart();
            this.SceneControl.ObjectSelectChanged += SceneControl_ObjectSelectChanged;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if(keyData == Keys.Escape)
                this.Close();
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void SceneControl_ObjectSelectChanged(object sender, ObjectSelectChangedEventArgs e)
        {
            if(this.Visible == false)
            {
                return;
            }
            if (SceneControl.Action != Action3D.Select) return;

            NameValueCollection hm = new NameValueCollection();
            var selection = this.SceneControl.Scene.FindSelection(true);
            var infoName = "信息";
            if(selection.Length == 0)
            {
                this.m_FloatWindow.SetInfo(infoName, hm);
                return;
            }
            var recordset = selection[0].ToRecordset();
            infoName = selection[0].Layer.Caption;
            var fieldInfos = recordset.GetFieldInfos();
            for (int i = 0; i < recordset.FieldCount; i++)
            {
                var caption = fieldInfos[i].Caption;
                var fieldName = fieldInfos[i].Name;
                if (fieldName.ToUpper().StartsWith("SM") && fieldName.ToUpper() != "SMID") continue;
                if (fieldName.ToUpper().StartsWith("SS")) continue;

                var valueObject = recordset.GetFieldValue(fieldName);
                var value = valueObject == null ? string.Empty : valueObject.ToString();
                hm.Add(caption,value);
            }
            this.m_FloatWindow.SetInfo(infoName, hm);
        }

        /// <summary>
        /// 加载透明层
        /// </summary>
        void InitChart()
        {
            m_FloatWindow = new BForm(this)
            {
                ShowInTaskbar = false,
                Topmost = true,
                Left = this.Left,
                Top = this.Top,
                Width = this.Width,
                Height = this.Height
            };
            m_FloatWindow.Show();
            m_FloatWindow.IsVisibleChanged += FloatWindow_IsVisibleChanged;

            this.m_FloatWindow.EllipseAll.MouseUp += EllipseAll_MouseUp;
            this.m_FloatWindow.EllipseWS.MouseUp += EllipseWS_MouseUp;
            this.m_FloatWindow.EllipseYS.MouseUp += EllipseYS_MouseUp;

            this.m_FloatWindow.ImageInfo.MouseUp += ImageInfo_MouseUp;
            this.m_FloatWindow.ImagePan.MouseUp += ImagePan_MouseUp;

            this.m_FloatWindow.ImageTerrain.MouseUp += ImageTerrain_MouseUp;
            InitData();
        }

        private void ImageTerrain_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            var lyrs = this.SceneControl.Scene.TerrainLayers;
            if (lyrs.Count == 0) return;
            var visible = lyrs[0].IsVisible;
            for (int i = 0; i < lyrs.Count; i++)
            {
                lyrs[i].IsVisible = !visible;
            }
        }

        private void ImagePan_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            SceneControl.Action = Action3D.Pan;
            SceneControl.Scene.Refresh();
        }

        private void ImageInfo_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            SceneControl.Action = SuperMap.UI.Action3D.Select;
            SceneControl.Scene.Refresh();
        }

        private void EllipseYS_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.InitData(30);
        }

        private void EllipseWS_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.InitData(80);
        }

        private void EllipseAll_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.InitData(100);
        }

        private void FloatWindow_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (m_FloatWindow.IsVisible == false)
            {
                this.Hide();
            }
            else
            {
                this.Show();
            }
        }

        public void ResposeWPF(string tag)
        {
            switch (tag)
            {
                case "STOP_CYCLE":
                    break;
                case "VIEWENTIRE":
                    var lookAtKeys = new List<string>()
                    {
                        "Longitude","Latitude","Tilt","Range","Altitude","Heading"
                    };
                    Dictionary<string, string> values = Commons.SerializeHelper.IniHelper.ReadLookAt(lookAtKeys.ToArray());
                    LookAt la = new LookAt();
                    try
                    {
                        la = new LookAt()
                        {
                            Longitude = double.Parse(values["Longitude"]),
                            Latitude = double.Parse(values["Latitude"]),
                            Tilt = double.Parse(values["Tilt"]),
                            Range = double.Parse(values["Range"]),
                            Altitude = double.Parse(values["Altitude"]),
                            Heading = double.Parse(values["Heading"])
                        };
                    }
                    catch(Exception ex)
                    {
                        Commons.LogHelper.Warn(ex.Message);
                        return;
                    }
                    if (la != null && la.IsValid)
                    {
                        SceneControl.Scene.Fly(la, 1000);
                    }
                    break;
            }
        }
        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);
            if (m_FloatWindow == null) return;
            if(this.Visible == false)
            {
                m_FloatWindow.Hide();
            }
            else
            {
                m_FloatWindow.Show();
                //AlertEvents();
            }
        }
        List<Geometry> AlertGeometrys = new List<Geometry>();
        private void AlertEvents()
        {
            var trackingLayer = this.SceneControl.Scene.TrackingLayer;
            
            for (var i= 0;i < AlertGeometrys.Count;i++)
            {
                var index = trackingLayer.IndexOf("ALERT_" + i);
                var index_Text = trackingLayer.IndexOf("ALERT_TEXT_" + i);
                var index_Ellipse = trackingLayer.IndexOf("ALERT_Ellipse_" + i);
                trackingLayer.Remove(index);
                trackingLayer.Remove(index_Text);
                trackingLayer.Remove(index_Ellipse);
            }

            var point1 = new Point3D(114,34,400);
            AddMarker(point1);
            
            void AddMarker(Point3D p3d)
            {
                var gp3d = new GeoPoint3D(p3d);
                var gp3dEll = new GeoPoint3D(p3d) { Z = 0 };
                var markerPath = Commons.Paths.ApplicationResourcesDir + "\\Symbols\\downArrow.gif";
                var markerEllipse = Commons.Paths.ApplicationResourcesDir + "\\Symbols\\markerEllipse.gif";
                var marderStyle = new GeoStyle3D()
                {
                    MarkerColor = Color.Red,
                    MarkerSize = 32,
                    MarkerFile = markerPath,
                    AltitudeMode = AltitudeMode.Absolute,
                    MarkerScale = 0.25
                };
                var marderEllStyle = new GeoStyle3D()
                {
                    MarkerColor = Color.Red,
                    MarkerSize = 32,
                    MarkerFile = markerEllipse,
                    AltitudeMode = AltitudeMode.ClampToGround,
                    MarkerScale = 1,
                    Marker3DRotateY = 90                    
                };
                var textLocation = gp3d.InnerPoint3D;
                GeoText3D geoText = new GeoText3D(new TextPart3D("实时告警", textLocation));

                gp3d.Style3D = marderStyle;
                gp3dEll.Style3D = marderEllStyle;

                Map.Basic.SuperMap.Styles.SetResultTextStyle(geoText,Color.Red);

                this.SceneControl.Scene.TrackingLayer.Add(geoText, "ALERT_0");

                this.SceneControl.Scene.TrackingLayer.Add(gp3d, "ALERT_TEXT_0");
                this.SceneControl.Scene.TrackingLayer.Add(gp3dEll, "ALERT_Ellipse_0");
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            if (m_FloatWindow == null) return;
            m_FloatWindow.Hide();
            base.OnClosed(e);
        }
        protected override void Dispose(bool disposing)
        {
            Hide();
        }
    }
}
